package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;
    @Override
    public List<Role> findAll() {
        return roleDao.findAll();
    }

    @Override
    public void add(Integer userId,Integer[] roleIds) {
        HashMap<String, Integer> map = new HashMap<>();
        for (Integer roleId : roleIds) {
            map.put("userId",userId);
            map.put("roleId",roleId);
            roleDao.add(map);
        }
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<Role> page = roleDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void editPermission(Integer roleId, Integer[] permissionIds) {
        roleDao.deleteOld(roleId);
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        for (Integer permissionId : permissionIds) {
            map.put("roleId",roleId);
            map.put("permissionId",permissionId);
            roleDao.editPermission(map);
        }
    }

    @Override
    public void addRole(Role role) {
        roleDao.addRole(role);
    }
}
